package com.hoshiicloud.saleorder.service.impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.customer.ReviewsImagesMapper;
import com.hoshiicloud.saleorder.mapper.customer.ReviewsMapper;
import com.hoshiicloud.saleorder.param.customer.ReviewsQueryParam;
import com.hoshiicloud.saleorder.service.customer.IReviewsService;
import com.hoshiicloud.user.entity.customer.Reviews;
import com.hoshiicloud.user.entity.customer.ReviewsImages;
import com.hoshiicloud.user.vo.customer.ReviewsDetailVO;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 平台商品评价 服务实现类
 * </p>
 *
 * @author Mr.Wu
 * @since 2019-04-28
 */
@Service
public class ReviewsServiceImpl extends ServiceImpl<ReviewsMapper, Reviews> implements IReviewsService {

    @Autowired
    private ReviewsMapper reviewsMapper;

    @Autowired
    private ReviewsImagesMapper reviewsImagesMapper;

    @Autowired
    private IdGeneratorService idGeneratorService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = {"Reviews"}, allEntries = true)
    @Logable(authName = "前台用户操作-平台商品评价信息管理-新增平台商品评价信息")
    public Response insert(Reviews param) {
        String id = idGeneratorService.queryGeneratorId();
        if (StringUtils.isBlank(id)) {
            throw new ServiceException(CommonError.error("id服务失败"));
        }
        // TODO 判断平台id是否有效
        // TODO 判断用户ID是否有效
        // TODO 判断SPUID是否有效
        // TODO 查看订单是否已评论过
        // TODO 新增追加评论

        param.setId(Long.parseLong(id));
        param.setCreatedtime(LocalDateTime.now());
        int count = reviewsMapper.insert(param);
        if (count <= 0) {
            throw new ServiceException(CommonError.error("新增失败"));
        }
        return Response.success("新增成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = {"Reviews"}, allEntries = true)
    @Logable(authName = "前台用户操作-平台商品评价信息管理-修改平台商品评价信息")
    public Response updateDataById(Reviews param) {
        // TODO 好评不可修改
        // TODO 初始评论在一定时间内可以修改一次
        // TODO 追加评论不可修改
        int count = reviewsMapper.updateById(param);
        if (count <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return Response.success("修改成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = {"Reviews"}, allEntries = true)
    @Logable(authName = "前台用户操作-平台商品评价信息管理-删除平台商品评价信息")
    public Response deleteDataById(String id) {
        // TODO 好评不可删除
        int count = reviewsMapper.deleteById(id);
        if (count <= 0) {
            throw new ServiceException(CommonError.error("删除失败"));
        } else {
            return Response.success("删除成功");
        }
    }

    @Override
    @Cacheable(cacheNames = "Reviews", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "前台用户操作-平台商品评价信息管理-查询平台商品评价信息详情")
    public Response getDetail(String id) throws Exception {
        ReviewsDetailVO data = reviewsMapper.selectReviewsAndExtraCommentOne(id);
        if (data == null) {
            return Response.failed("数据不存在");
        } else {
            // 查询评论资源
            QueryWrapper<ReviewsImages> queryWrapper = new QueryWrapper<ReviewsImages>();
            queryWrapper.eq("review_id", data.getId());
            List<ReviewsImages> reviewsImages = reviewsImagesMapper.selectList(queryWrapper);
            data.setReviewResList(reviewsImages);
            if (data.getExtraId() != null) {
                queryWrapper = new QueryWrapper<ReviewsImages>();
                queryWrapper.eq("review_id", data.getExtraId());
                List<ReviewsImages> reviewsImagesExtra = reviewsImagesMapper.selectList(queryWrapper);
                data.setExtraReviewResList(reviewsImagesExtra);
            }
            return Response.data(data);
        }
    }

    @Override
    @Cacheable(cacheNames = "Reviews", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5('Param(Param=' + #param.toString() + ')')")
    @Logable(authName = "前台用户操作-平台商品评价信息管理-查询平台商品评价信息列表")
    public Response getList(ReviewsQueryParam param) {
        // TODO 查询时一并查询追加评论
        return Response.data(reviewsMapper.selectReviewsAndExtraCommentList(param));
    }

    @Override
    @Cacheable(cacheNames = "Reviews", key = "T(com.hoshiicloud.common.utils.DigestUtils).md5('Page(current=' + #page.getCurrent() + ', size=' + #page.getSize() + '), Param(Param=' + #param.toString() +  ')')")
    @Logable(authName = "前台用户操作-平台商品评价信息管理-分页查询平台商品评价信息")
    public Response getPage(IPage<Reviews> page, ReviewsQueryParam param) {
        // TODO 查询时一并查询追加评论
        IPage<ReviewsDetailVO> data = reviewsMapper.selectReviewsAndExtraCommentPage(page, param);
        List<ReviewsDetailVO> dataList = data.getRecords();
        if (dataList != null && dataList.size() > 0) {
            // 组装ID列表,搜索资源
            List<Long> reviewsIdList = new ArrayList<Long>();
            for (ReviewsDetailVO reviewsDetailVO : dataList) {
                reviewsIdList.add(reviewsDetailVO.getId());
                if (reviewsDetailVO.getExtraId() != null) {
                    reviewsIdList.add(reviewsDetailVO.getExtraId());
                }
            }
            List<ReviewsImages> resList = reviewsImagesMapper
                    .selectList(new QueryWrapper<ReviewsImages>().in("review_id", reviewsIdList));
            Iterator<ReviewsImages> resIterator = resList.iterator();
            // 组装返回数据
            for (ReviewsDetailVO reviewsDetailVO : dataList) {
                while (resIterator.hasNext()) {
                    ReviewsImages reviewsImages = resIterator.next();
                    if (reviewsImages.getReviewId().equals(reviewsDetailVO.getId())) {
                        List<ReviewsImages> tList = reviewsDetailVO.getReviewResList();
                        if (tList == null) {
                            tList = new ArrayList<ReviewsImages>();
                            tList.add(reviewsImages);
                            reviewsDetailVO.setReviewResList(tList);
                        } else {
                            tList.add(reviewsImages);
                        }
                        resIterator.remove();
                    } else if (reviewsDetailVO.getExtraId() != null
                            && reviewsImages.getReviewId().equals(reviewsDetailVO.getExtraId())) {
                        List<ReviewsImages> tList = reviewsDetailVO.getExtraReviewResList();
                        if (tList == null) {
                            tList = new ArrayList<ReviewsImages>();
                            tList.add(reviewsImages);
                            reviewsDetailVO.setExtraReviewResList(tList);
                        } else {
                            tList.add(reviewsImages);
                        }
                        resIterator.remove();
                    }
                }
            }
        }
        return Response.data(data);
    }
}
